package com.example.fist.util.mail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class Mailbox {

    private String EmailPassword="xgvdmzlegksoddde";
    private Message message;
    private Transport transport;

    /**
     *
     * @param Addressee 接受方邮箱地址
     * @param Text 内容
     * @throws AddressException
     * @throws MessagingException
     */
    public Mailbox(String Addressee ,String Text,String name,String title) throws AddressException,  MessagingException{

       
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接  ---一般都使用
        properties.put("mail.debug", "false");//设置是否显示debug信息  true 会在控制台显示相关信息
        //得到回话对象
        Session session = Session.getInstance(properties);

        // 获取邮件对象
        message= new MimeMessage(session);

        //设置发件人邮箱地址
       // message.setFrom(new InternetAddress(name+"<2829852313@qq.com>"));
        InternetAddress i=new  InternetAddress("<2829852313@qq.com>");
        try {
            i.setPersonal("及第","utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        message.setFrom(i);

        //设置收件人地址
        message.setRecipients(RecipientType.TO, new InternetAddress[] { new InternetAddress(Addressee) });



        //设置邮件标题
        message.setSubject(title);

        //设置邮件内容
        message.setText(Text);
      //  message.setContent("<a href=\"http:\\127.0.0.1\">http:\\\\127.0.0.1</a>","text/html");
        //得到邮差对象
        transport= session.getTransport();

        //连接自己的邮箱账户
        transport.connect("2829852313@qq.com", EmailPassword);//密码为刚才得到的授权码
    }

    /**
     *
     * @return 发送是否成功
     */
    public boolean sendMessage() {
        try {
            transport.sendMessage(message, message.getAllRecipients());
            return true;
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
}

